import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import java.io.File;

import java.sql.SQLException;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;
import java.util.concurrent.TimeUnit;

public class SAXLoader extends RecursiveAction {
    public static void main(String[] args) throws InterruptedException, SQLException {
        ForkJoinPool taskPool = new ForkJoinPool(3);

        long loadingTime = System.currentTimeMillis();

        taskPool.invoke(new SAXLoader());

        taskPool.shutdown();
        if (!taskPool.awaitTermination(DBConnection.DB_TIMEOUT, TimeUnit.SECONDS)) {
            taskPool.shutdownNow();
        }

        long fetchingTime = System.currentTimeMillis();
        loadingTime = fetchingTime - loadingTime;

        System.out.println("Voting station work times: ");
        DBConnection.printStationWorkTimes();
        System.out.println("Duplicated voters: ");
        DBConnection.printVoterCounts();

        System.out.println("Loading time " + loadingTime / 1000 + " sec");
        System.out.println("Fetching time " + (System.currentTimeMillis() - fetchingTime) + " ms");
    }

    @Override
    protected void compute() {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser;

        try {
            parser = factory.newSAXParser();
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

        try (
            SAXHandler handler = new SAXHandler()
        ) {
            parser.parse(new File(Loader.fileName), handler);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
